<template>
  <d2-container>
    <el-main>

    <el-dialog title="校区列表" :visible.sync="showSchoolList">

                        <el-input placeholder="输入校区名字" v-model="schoolname" size="small">
                            <el-button slot="append" icon="el-icon-search" @click="searchSchool"></el-button>
                        </el-input>

                        <el-table :data="schoolList">
                            <el-table-column property="name" label="学校名称"></el-table-column>
                            <el-table-column label='操作'>
                                <template slot-scope="scope" >
                                    <el-button  @click="addSchool(scope.row)" type="text">添加</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div slot="footer" class="dialog-footer">
                            <el-button type="primary" @click="showSchoolList = false">确认</el-button>
                        </div>
    </el-dialog>

      <el-form ref="staffForm" :model="staffForm" label-width="120px" label-position="left" 
               :rules="formRules">
               
        <el-form-item label="姓名" prop="name">
          <el-input placeholder="请输入员工姓名" v-model="staffForm.name" :disabled="disabled"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="staffForm.gender" :disabled="disabled">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="入职日期" prop="entryDate">
          <el-date-picker
                  v-model="staffForm.entryDate"
                  type="date"
                  placeholder="选择入职日期："
                  :disabled="disabled"
          ></el-date-picker>
        </el-form-item>


        <el-form-item label="出生" prop="birthday">
          <el-date-picker
                  v-model="staffForm.birthday"
                  type="date"
                  placeholder="选择出生年月"
                  :disabled="disabled"
          ></el-date-picker>
        </el-form-item>


        <el-form-item label="电话" prop="cellphone">
          <el-input placeholder="请输入电话" v-model.number="staffForm.cellphone" :disabled="disabled"></el-input>
        </el-form-item>

        <el-form-item label="家庭地址" prop="homeAddress">
          <el-input placeholder="请输入家庭地址" v-model="staffForm.homeAddress" :disabled="disabled"></el-input>
        </el-form-item>

         <el-form-item label="授课提成(%)" prop="staffBonus">
          <el-input placeholder="如果不上课，输入0" v-model.number="staffForm.staffBonus" :disabled="disabled" type='number' step='0.1'></el-input>
        </el-form-item>


        <el-form-item label="所在部门" prop="department">
          <el-select
                  v-model="staffForm.department"
                  filterable
                  placeholder="可输入名称搜索"
                  @change="departmentSelected"
                  :disabled="disabled">
            <el-option
                    v-for="item in departmentList"
                    :key="item._id"
                    :label="item.name"
                    :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="职位" prop="position">
          <el-select
                  v-model="staffForm.position"
                  filterable
                  :disabled="disabled">
            <el-option
                    v-for="item in positionList"
                    :key="item._id"
                    :label="item.name"
                    :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item>

<!--         <el-form-item label="所在校区" prop="school">
          <el-select
            v-model="staffForm.school"
            filterable
            placeholder="可输入名称搜索"
            @change="schoolSelected"
            :disabled="disabled"
          >
            <el-option
              v-for="item in schoolList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item> -->

        <el-row :span="6" style="margin-top:10px;height:40px"><span style='width:2px;height:100%;background-color:rgb(52, 178, 211) ;color: rgb(52, 178, 211);margin-right: 3px'>_</span>
          所在校区
          <el-button @click="showSchoolList = true" type='primary' style='height:30px;position: relative;top:0px;font-size: 14px;padding: 5px;margin-left:50px;display: inline-block;' :disabled='disabled'>添加校区
          </el-button>
      </el-row>

            <el-row style='background-color:white;width: 100%;position: relative;border-width: 1px;border-color: #D4DFE5;border-style: solid;margin-bottom:20px;margin-top: 10px;border-width: 1px;border-color: #D4DFE5;border-style: solid;'  >
            
            </div>

             <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5">
            </div>

            <div style="width: 100%;position: relative;">
                <div v-for='(school,index) in staffForm.school' style="margin-bottom:10px;height:60px;position: relative;">
                    <div style="position: relative;left:30px;display: inline-block;width: 300px;height: 60px;line-height: 60px">{{school.name}}</div>
                    <button style="height:30px;width: 30px;background-color: #F6E4E7;border-style: solid;border-width: 1px;border-color: #FB6363;border-radius: 3px;position: absolute;top:20px;right:50px" @click="removeSchool(index)"><i class="el-icon-close" style="color: #FB6363;" :disabled="!edit"></i> 
                    </button>
                  <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5;top:0px"></div>
                </div>
            </div>

             <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5;top:40px">
            </div>

        </el-row>

<!--         <el-form-item label="上级">
          <el-select
                  v-model="staffForm.reportTarget"
                  filterable
                  multiple
                  :disabled="disabled"
          >
            <el-option
                    v-for="item in reportTargetList"
                    :key="item._id"
                    :label="item.name"
                    :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item> -->

     <!--    <el-form-item label="带新赏金" prop="inviteProportion">
          <el-input placeholder="请输入比例" type="number" v-model.number="staffForm.inviteProportion" :disabled="disabled" min="0"></el-input>
        </el-form-item>

        <el-form-item label="续课比例" prop="continuousProportion">
          <el-input placeholder="请输入比例" type="number" v-model.number="staffForm.continuousProportion" :disabled="disabled" min="0"></el-input>
        </el-form-item>

        <el-form-item label="教材比例" prop="productProportion">
          <el-input placeholder="请输入比例" type="number" v-model.number="staffForm.productProportion" :disabled="disabled" min="0"></el-input>
        </el-form-item>
        <el-form-item label="教课奖金（元）" prop="classBonus">
          <el-input placeholder="请输入金额" type="number" v-model.number="staffForm.classBonus" :disabled="disabled" min="0"></el-input>
        </el-form-item>

        <el-form-item label="负责班级">
          <el-transfer
                  filterable
                  filter-placeholder="请输入班级名称"
                  v-model="staffForm.classSelected"
                  :data="classList"
                  :titles="['全部班级', '负责班级']"
          ></el-transfer>
        </el-form-item> -->

      </el-form>
    </el-main>
    <el-footer style="text-align: center">
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="resetForm('staffForm')">重置</el-button>
      <el-button @click="edit" v-show="editShow">修改</el-button>
    </el-footer>
  </d2-container>
</template>

<script>
import request from "@/plugin/axios";
import {mapState} from "vuex"
export default {
  data() {
    return {
      staffForm: {
        name: undefined,
        gender: undefined,
        entryDate: undefined,
        birthday: undefined,
        cellphone: undefined,
        homeAddress: undefined,
        reportTarget: undefined,
        position: undefined,
        department: undefined,
        school: undefined,
        classSelected: undefined,
        inviteProportion: 0,
        continuousProportion: 0,
        productProportion: 0,
        classBonus : 0,
        staffBonus : undefined,
        schoolList : [],
        staffSchool : undefined

      },
      schoolname : '',
      showSchoolList : false,
      editShow: false,
      disabled: false,
      id: undefined,
      startDate: undefined,
      schoolList: [],
      departmentList: [],
      positionList: undefined,
      reportTargetList: undefined,
      classList: [],

      formRules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
       
        gender: [
          {required: true, message: '请选择性别', trigger: 'change'}
        ],
        age: [
          {required: true, message: '请输入家长年龄', trigger: 'change'},
          {type: 'number', min: 5, max: 100, message: '年龄范围在5-100之间', trigger: 'change'}

        ],
        school: [
          {required: true, message: '请选择所在校区', trigger: 'change'}
        ],
        
        student: [
          {required: true, message: '请选择学生', trigger: 'change'}
        ],
        // homeAddress: [
        //   {required: true, message: '请输入地址', trigger: 'change'}
        // ],

        cellphone: [
          {required: true, message: '手机号不能为空', trigger: 'change'},
        ],
        birthday: [
          {type: 'date', required: true, message: '请选择出生日期', trigger: 'blur'}
        ],
        entryDate: [
          {type: 'date', required: true, message: '请选择出生日期', trigger: 'blur'}
        ],
        selectedSchoolList: [
          {type: 'array', required: true, message: '请选择购买校区', trigger: 'blur'}
        ],
        selectedStudentList: [
          {type: 'array', required: true, message: '请选择购买学生', trigger: 'blur'}
        ],
        productOrder: [
          {type: 'array', required: true, message: '请选择采购商品', trigger: 'blur'}
        ],
        payWay: [
          {required: true, message: '请选择支付方式', trigger: 'change'}
        ],
        payStatus: [
          {required: true, message: '请选择支付状态', trigger: 'change'}
        ],
        hasBonus: [
          {required: true, message: '请选择是否提成', trigger: 'change'}
        ],
        type: [
          {required: true, message: '请选择充值类型', trigger: 'change'}
        ],
        discount: [
          {required: true, min: 0, type: 'number', message: '请输入合法优惠金额', trigger: 'change'}
        ],
        course: [
          {type: 'array', required: true, message: '请选择课程', trigger: 'blur'}
        ],
        total: [
          {required: true, message: '价格不能为空', trigger: 'change'},
          {type: 'number', message: '请输入合法价格', trigger: 'change'}
        ],
        hour: [
          {required: true, message: '时长不能为空', trigger: 'change'},
          {type: 'number', message: '请输入时长', trigger: 'change'}
        ],
        storage: [
          {required: true, message: '价格不能为空', trigger: 'change'},
          {type: 'number', message: '请输入整数', trigger: 'change'}
        ],
        sellingPrice: [
          {required: true, message: '价格不能为空', trigger: 'change'},
          {type: 'number', message: '请输入整数', trigger: 'change'}
        ],
        wholeSalePrice: [
          {required: true, message: '价格不能为空', trigger: 'change'},
          {type: 'number', message: '请输入整数', trigger: 'change'}
        ],
        costPrice: [
          {required: true, message: '价格不能为空', trigger: 'change'},
          {type: 'number', message: '请输入整数', trigger: 'change'}
        ],
        inviteProportion: [
          // {required: true, message: '比列不能为空', trigger: 'change'},
          {type: 'number', min:0,message: '请输入整数', trigger: 'change'}
        ],
        continuousProportion: [
          // {required: true, message: '比列不能为空', trigger: 'change'},
          {type: 'number',min:0, message: '请输入整数', trigger: 'change'}
        ],
        productProportion: [
          // {required: true, message: '比列不能为空', trigger: 'change'},
          {type: 'number',min:0, message: '请输入整数', trigger: 'change'}
        ],
        staffBonus: [
          // {required: true, message: '比列不能为空', trigger: 'change'},
          {type: 'number', min:0, message: '请输入整数', trigger: 'change',required:true}
        ],
        reportTarget: [
          {type: 'array', required: true, message: '请选择上级', trigger: 'blur'}
        ],
        // position: [
        //   {type: 'array', required: true, message: '请选择职位', trigger: 'blur'}
        // ],

        department:[
          {required: true, message: '请选择部门', trigger: 'change'}
        ],
                position:[
          {required: true, message: '请选择职位', trigger: 'change'}
        ],
      },
    };
  },
  computed:{
    ...mapState('d2admin/user',['info'])
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    edit() {
      this.disabled = false;
    },
    getSchoolList() {
      // this.schoolList = this.info.school;
      // this.staffForm.school = this.schoolList[0]._id;
      let data = {};
          data.page = 1;
          data.pageSize = 9999999;
          if (this.schoolname != ''){
            data.name = this.schoolname
          }
          request({
            url: "/school/getSchoolList",
            method: "post",
            data
          }).then(res => {
            this.schoolList = res.data.school;
            this.schoolname = ''
            console.log(res.data.school,'dsds')
          });

      // this.getClassList(1, 9999, this.staffForm.school);

      // this.info.role.forEach(value=>{
      //   if (value.name==='root') {
      //     let data = {};
      //     data.page = 1;
      //     data.pageSize = 9999999;
      //     request({
      //       url: "/school/getSchoolList",
      //       method: "post",
      //       data
      //     }).then(res => {
      //       this.schoolList = res.data.school;
      //     });
      //   }
      // })
    },

    addSchool(e){
      if (this.staffForm.school.map(function(e){return e._id}).indexOf(e._id) == -1){
        this.staffForm.school.push(e)
      }
      
    },

    removeSchool(index){
      if (index != 0){
        this.staffForm.school.splice(index,1)
      }
      else{
        this.$message('不能删除该员工主校区')
      }
    },
    getDepartmentList(page, pageSize, school) {
      // this.staffForm.department = undefined
      let data = {};
      data.page = page;
      data.pageSize = pageSize;
      data.school = school;
      request({
        url: "/department/getDepartmentList",
        method: "post",
        data
      }).then(res => {
          this.departmentList = res.data.department;
          let index = this.departmentList.map(function(e){return e._id}).indexOf(this.staffForm.department)
          if (index == -1){
            this.staffForm.department = undefined
          }
      });
    },
    getPositionList(page) {
      request({
        url: "/position/getPositionList",
        method: "post",
        data : {school:this.staffSchool}
      }).then(res => {
        this.positionList = res.data.position;
        // 返回数据
      });
    },
    getReportTargetList(page, pageSize) {
      let data = {};
      (data.page = page), (data.pageSize = pageSize);
      // data.department = this.staffForm.department
      data.school = this.school
      request({
        url: "/staff/getStaffList",
        method: "post",
        data
      }).then(res => {
        this.reportTargetList = res.data.staff;
        // 返回数据
      });
    },

    searchSchool(){
      this.getSchoolList()
    },
    getClassList(page, pageSize, school) {
      let data = {};
      data.page = page;
      data.pageSize = pageSize;
      data.school = school;
      request({
        url: "/class/getClassList",
        method: "post",
        data
      }).then(res => {
        this.classList = []
        for (let i = 0; i < res.data.class.length; i++) {
          let key = res.data.class[i]._id;
          let label = res.data.class[i].name;
          this.classList.push({key: key, label: label})
        }
        if (this.$route.query.id) {
          this.getStaffOne(this.$route.query.id);
        }

      });
    },
    schoolSelected() {
      this.getDepartmentList(1, 9999, this.staffForm.school);
    },
    departmentSelected() {
      // this.getClassList(1, 99999, this.staffForm.school);
      this.getReportTargetList(1, 99999);
    },
    submit() {

      let data = {};
      let url = "/staff/addStaff";
      if (this.id != undefined) {
        data.staff = this.id;
        url = "/staff/updateStaff";
      }
      data.name = this.staffForm.name;
      data.gender = this.staffForm.gender;
      data.cellphone = this.staffForm.cellphone;
      data.homeAddress = this.staffForm.homeAddress;
      data.entryDate = this.staffForm.entryDate;
      data.position = this.staffForm.position;
      data.reportTarget = this.staffForm.reportTarget;
      data.department = this.staffForm.department;
      // data.school = this.staffForm.school;
      data.birthday = this.staffForm.birthday;
      data.inviteProportion = this.staffForm.inviteProportion;
      data.productProportion = this.staffForm.productProportion;
      data.continuousProportion = this.staffForm.continuousProportion;
      data.class = this.staffForm.classSelected;
      data.staffBonus = this.staffForm.staffBonus
      data.school = this.staffForm.school
      request({
        url: url,
        method: "post",
        data
      }).then(res => {
        if (res.code == 200) {
          this.refresh = true
          this.staffForm = {
        name: undefined,
        gender: undefined,
        entryDate: undefined,
        birthday: undefined,
        cellphone: undefined,
        homeAddress: undefined,
        reportTarget: undefined,
        position: undefined,
        department: undefined,
        // school: undefined,
        classSelected: undefined,
        inviteProportion: 0,
        continuousProportion: 0,
        productProportion: 0,
        classBonus : 0,
        staffBonus : undefined,
        schoolList : [],
        staffSchool : undefined

      }
          this.$router.push({path: "/staff-list"})
          this.$alert("", "提交成功", {
            confirmButtonText: "确定"
          });
        }
        // 返回数据
      });
    },
    getStaffOne(id) {
      request({
        url: "/staff/getStaffOne",
        method: "post",
        data: {id: id}
      }).then(res => {
        if (res.code == 200) {
          this.id = res.data._id;
          this.staffForm.name = res.data.name;
          this.staffForm.gender = res.data.gender;
          this.staffForm.cellphone = res.data.cellphone;
          this.staffForm.homeAddress = res.data.homeAddress;
          this.staffForm.entryDate = res.data.entryDate;
          this.staffForm.position = res.data.position != undefined ? res.data.position._id : undefined;
          this.staffForm.reportTarget = res.data.reportTarget.map(value => value._id);
          this.reportTargetList = res.data.reportTarget;
          this.staffForm.department = res.data.department;
          this.staffForm.school = res.data.school;
          this.staffForm.birthday = res.data.birthday;
          // this.staffForm.continuousProportion = res.data.continuousProportion;
          // this.staffForm.productProportion = res.data.productProportion;
          // this.staffForm.inviteProportion = res.data.inviteProportion;
          this.staffForm.classSelected = res.data.class.map(value => value._id);
          this.staffForm.staffBonus = res.data.staffBonus != undefined ? res.data.staffBonus : undefined
          // this.classBonus = res.data.classBonus == undefined ? 0 :res.data.classBonus
          this.getDepartmentList(1, 9999, res.data.school[0]._id);
          this.staffSchool = res.data.school[0]._id
          this.getPositionList(1, 99999);

        }
      });
    },
    load(){
    this.school = this.info.school[0]._id
    this.id = this.$route.query.id
    this.staffSchool = this.school
     if ((this.info.school[0].headquarter == 1) || (this.info.school[0].headquarter == 2)){
        this.disabled = false;
      }
      else{
        this.disabled = false
      }
    if (this.$route.query.id) {
      this.getStaffOne(this.$route.query.id);
      this.staffSchool = undefined
      // this.getSchoolList();
      this.disabled = true
      this.editShow = true;
     
      
    } else {
      this.getPositionList(1, 99999);
      // this.getSchoolList();
      this.getDepartmentList(1, 9999, this.info.school[0]._id);
      this.staffForm.school = [this.info.school[0]]
      this.editShow = false
      this.disabled = false
    }
  },
  },

  
        beforeRouteLeave(to,from,next){
        if (this.refresh){
          to.meta.refresh = 'a'
          this.refresh = undefined
        }
        if (this.id == undefined){
            from.meta.keep = true
            from.meta.staffForm = this.staffForm
        }

        next()
        },
        beforeRouteEnter(to,from,next){
            if (to.meta.keep){
                to.meta.keep = undefined
                next(v=>{
                  v.staffForm = to.meta.staffForm
                  to.meta.staffForm = undefined
                  to.meta.keep = undefined
                  v.load()
                })
            }
            else{
                next(v=>{
                    v.load()
                })
                // next()
            }

        },

  created() {
    this.load()
  }
};
</script>
